package com.moonspring.dao;

import org.bson.Document;

import com.mongodb.MongoWriteException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.moonspring.db.mongodb;
import com.moonspring.model.UserModel;
import com.moonspring.util.Contans;

public class UserDao {
	//登录
	public UserModel userLogin(UserModel u){
		u.setLginStat(-1);
		mongodb mym = null;
		try {
			mym = new mongodb(Contans.DBHOST, Contans.DBPORT);
			MongoDatabase db = mym.getConnection(Contans.DBNAME);
			MongoCollection<Document> dc = db.getCollection(Contans.USERTABLE);
			Document query = new Document("name",u.getUserName());
			query.put("pwd", u.getPwd());
			FindIterable<Document> useri = dc.find(query);
			MongoCursor<Document> userc = useri.iterator();
			if(userc.hasNext()){
				u.setLv(userc.next().getInteger("lv"));
				u.setLginStat(1);
			}
			else {
				u.setLginStat(-3);
			}
		} catch (MongoWriteException e) {
			e.printStackTrace();
			if (e.getCode() == 11000) {
				u.setLginStat(-2);
			}
		} catch (Exception e) {
			e.printStackTrace();
			u.setLginStat(-1);
		} finally {
		}
		return u;
	}
	
	public int addUser(UserModel u){
		int r = -1;
		mongodb mym = null;
		try {
			mym = new mongodb(Contans.DBHOST, Contans.DBPORT);
			MongoDatabase db = mym.getConnection(Contans.DBNAME);
			MongoCollection<Document> dc = null;
			boolean t = true;
			int lv = u.getLv();
			if(3 == lv){
				t = false;
				dc = db.getCollection(Contans.REGISTERCODE);
				Document query = new Document("stat",1);
				query.put("code", u.getRegistCode());
				FindIterable<Document> rci = dc.find(query);
				MongoCursor<Document> rcc = rci.iterator();
				if(rcc.hasNext()){
					dc.updateOne(query, new Document("$set",new Document("stat",2)));
					t = true;
				} else {
					r = -2;
				}
			}
			if(t){
				dc = db.getCollection(Contans.USERTABLE);
				Document user = new Document("name",u.getUserName());
				user.put("pwd", u.getPwd());
				user.put("lv", lv);
				dc.insertOne(user);
				r = 1;
			}
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}  finally {
			if(mym != null){
				mym.close();
			}
		}
		return r;
	}
}
